/* global hexo */
var fs = require('fs');
'use strict';

var pathFn = require('path');
var _ = require('lodash');
var cheerio = require('cheerio');

function startsWith(str, start) {
  return str.substring(0, start.length) === start;
}

function removePrefix(str, prefix = "_") {
  let find = str.indexOf(prefix);
  if (find >= 0) {
    return str.substr(find + 1);
  }
  return str;
}
function removePostfix(str, postfix = ".md") {
  let diff = str.length - postfix.length;
  if (diff > 0) {
    if (str.substr(diff).toLowerCase() == postfix.toLowerCase()) {
      return str.substr(0, diff);
    }
  }
  return str;
}

function getShowName(pathname,self){
  let str = pathname;
  if(str == "index.html"){
    return self.__('index');
  }
  let find = str.lastIndexOf("/");
  if(find >= 0 ){
    str = str.substr(find+1);
  }
  return removePrefix(removePostfix(str,".html"));
}


function ReadDir(path) {
  let info = { is_dir: true, name: '', subs: [] };
  let dirs = fs.readdirSync(path, { withFileTypes: true });
  let subs = info.subs;
  for (let dir of dirs) {
    if (dir.isDirectory()) {
      let sub = ReadDir(path + "/" + dir.name);
      sub.name = dir.name;
      subs.push(sub);
    }
    else if (dir.isFile()) {
      subs.push({ is_dir: false, name: dir.name });
    }
  }
  return info;
}


var DOCS = ReadDir("source");

hexo.extend.helper.register('doc_sidebar', function (className) {
  var selected_path = pathFn.dirname(this.path) + "/" + pathFn.basename(this.path);
  var results = [];
  //genSidebar(DOCS.subs, "", results, selected_path, className,this);
  for (let dir of DOCS.subs) {
    if (!dir.is_dir || dir.subs.length == 0)
      continue;
    results.push('<strong class="' + className + '-title">' + removePrefix(dir.name) + '</strong>');
    for (let file of dir.subs) {
      if(file.is_dir)
        continue;
      let name = removePostfix(file.name, ".md");
      if (name == file.name)
        return; // only deal md file
      var link = dir.name + "/" + name + '.html';
      var itemClass = className + '-link';
      if (link === selected_path)
        itemClass += ' current';
      results.push('<a href="' + this.url_for(link) + '" class="' + itemClass + '">' + removePrefix(name) + '</a>');
    }
  }
  return results.join("");
});
/* 多层目录的处理方式
function genSidebar(infos, curr_path, results, selected_path, className, self) {
  for (let info of infos) {
    if (info.is_dir == true) {
      if(info.subs.length > 0){
        results.push('<strong class="' + className + '-title">' + removePrefix(info.name) + '</strong>');
        genSidebar(info.subs, curr_path + "/" + info.name, results, selected_path, className, self);
      }
    } else {
      let name = removePostfix(info.name, ".md");
      if (name == info.name)
        return; // only deal md file
      var link = curr_path + "/" + name + '.html';
      var itemClass = className + '-link';
      if (link === selected_path)
        itemClass += ' current';
      results.push('<a href="' + self.url_for(link) + '" class="' + itemClass + '">' + removePrefix(name) + '</a>');
    }
  }
}
*/

hexo.extend.helper.register('header_logo', function() {
  let logos = ['logo.svg','logo.png','logo.jpg','logo.jpeg'];
  for(let logo of logos){
    if(fs.existsSync("source/"+logo)){
      return '<img id="logo" src='+this.url_for(logo)+'></img>';
    }
  }
  return '';
});

hexo.extend.helper.register('page_title', function() {
  if(this.page.title && this.page.title != ""){
    return this.page.title;
  }
  let name =  pathFn.basename(this.path);
  if(name == "index.html"){
    return this.__('index');
  }
  return removePrefix(removePostfix(name,".html"));
});

hexo.extend.helper.register('page_nav', function() {
  var selected_path = pathFn.dirname(this.path) + "/" + pathFn.basename(this.path);
  let list = ['./index.html'];
  let keys = [this.__('index')];

  for (let dir of DOCS.subs) {
    if (!dir.is_dir || dir.subs.length == 0)
      continue;
    for (let file of dir.subs) {
      if(file.is_dir)
        continue;
      let name = removePostfix(file.name, ".md");
      if (name == file.name)
        return; // only deal md file
      let link = dir.name + "/" + name + '.html';
      list.push(link);
      keys.push(name);
    }
  }
  let index = list.indexOf(selected_path);
  let result = '';

  if (index > 0) {
    result += '<a href="' + this.url_for(list[index - 1]) + '" class="article-footer-prev" title="' + removePrefix(keys[index - 1]) + '">'
      + '<i class="fa fa-chevron-left"></i><span>' + this.__('page.prev') + '</span></a>';
  }

  if (index >= 0 && index < keys.length - 1) {
    result += '<a href="' + this.url_for(list[index + 1]) + '" class="article-footer-next" title="' + removePrefix(keys[index + 1]) + '">'
      + '<span>' + this.__('page.next') + '</span><i class="fa fa-chevron-right"></i></a>';
  }

  return result;
});

hexo.extend.helper.register('header_menu', function (className) {
  let items = this.theme.menu;
  var results = [];
  var self = this;

  for(let item of items){
    results.push('<a href="' + self.url_for(item) + '" class="' + className + '-link">' + getShowName(item,this) + '</a>');
  }

  return results.join('');
});


hexo.extend.helper.register('page_anchor', function (str) {
  var $ = cheerio.load(str, { decodeEntities: false });
  var headings = $('h1, h2, h3, h4, h5, h6');

  if (!headings.length) return str;

  headings.each(function () {
    var id = $(this).attr('id');

    $(this)
      .addClass('article-heading')
      .append('<a class="article-anchor" href="#' + id + '" aria-hidden="true"></a>');
  });

  return $.html();
});




hexo.extend.helper.register('hexo_version', function () {
  return this.env.version;
});
